// ==UserScript==
// @name        XMLHttpRequest
// @description An XMLHttpRequest shim using GM_xmlhttpRequest
// @version     1.0.1
// @author      Lari Rasku <lari.o.rasku@gmail.com>
// @license     MIT
// ==Requires==
// @grant       GM_xmlhttpRequest
// ==/UserScript==

// Copyright (c) 2014 Lari Rasku <lari.o.rasku@gmail.com>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

function XMLHttpRequest() {
  this.headers = {};
  this.upload = {};
}

XMLHttpRequest._BINARY_RESPONSES = [
  'arraybuffer',
  'blob',
  'moz-blob',
  'moz-chunked-arraybuffer'
];

XMLHttpRequest._EVENTS = [
  'onabort',
  'onerror',
  'onload',
  'onprogress',
  'onreadystatechange',
  'ontimeout',
];

XMLHttpRequest.prototype._responseWrapper = function (type, callback) {
  return (function (response) {
    this.readyState = response.readyState;
    this.responseHeaders = response.responseHeaders;
    this.responseText = response.responseText;
    this.status = response.status;
    this.statusText = response.statusText;
    if (this.status === 200) {
      if (this.response_type === 'arraybuffer') {
        var data = new Uint8Array(this.responseText.length);
        for (var i = this.responseText.length; i--;) {
          data[i] = this.responseText.charCodeAt(i) & 0xFF;
        }
        this.response = data.buffer;
      } else if (this.response_type === 'blob') {
        // this probably won't work as intended
        this.response = new Blob([this.responseText]);
      } else if (this.response_type === 'json') {
        this.response = JSON.parse(this.responseText);
      }
    }
    callback.call(this, {
      target: this,
      type: type.substring(2),
      lengthComputable: response.lengthComputable,
      total: response.total,
      loaded: response.loaded,
    });
  }).bind(this);
}

XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  this.method = method;
  this.url = url;
  this.synchronous = !async;
  this.user = user;
  this.password = password;
}

XMLHttpRequest.prototype.setRequestHeader = function (header, value) {
  this.headers[header] = value;
}

XMLHttpRequest.prototype.overrideMimeType = function (mimetype) {
  this.overrideMimeType = mimetype;
}

XMLHttpRequest.prototype.send = function (data) {
  if (data && typeof data !== 'string' && !(data instanceof String)) {
    this.binary = true;
    var reader = new FileReader();
    reader.onload = (function (e) { this.send(e.target.result) }).bind(this);
    reader.onerror = this.onerror;
    reader.readAsBinaryString(new Blob([data]));
    return;
  }
  
  this.data = data;
  this.response_type = this.responseType;
  delete this.responseType;
  
  if (XMLHttpRequest._BINARY_RESPONSES.indexOf(this.response_type) !== -1) {
    this.overrideMimeType('plain/text; charset=x-user-defined');
  }
  
  for (var i = 0, event; event = XMLHttpRequest._EVENTS[i]; ++i) {
    if (event in this) {
      this[event] = this._responseWrapper(event, this[event]);
    }
  }
  
  for (var i = 0, event; event = XMLHttpRequest._EVENTS[i]; ++i) {
    if (event in this.upload) {
      this.upload[event] = this._responseWrapper(event, this.upload[event]);
    }
  }
  
  GM_xmlhttpRequest(this);
  return;
}
